const path = require('path')
const resolve = (...args) => path.resolve(__dirname, ...args)
const spiderUserAgentPattern = require('./utils/spider').spiderUserAgentPattern

const logger = require('pino')({
  prettyPrint: {
    colorize: true,
    translateTime: 'yyyy-mm-dd HH:MM:ss.l',
    ignore: 'pid,hostname'
  }
})

const SERVER_PORT = process.env.SERVER_PORT || 1334
const express = require('express')
const app = express()

// health check
app.get('/health', function (req, res) {
  res.sendStatus(200)
})

// app.use(require('serve-favicon')(resolve('public/favicon.png')))

app.use(require('helmet')({
  contentSecurityPolicy: false,
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' }
}))

app.use(require('rendertron-middleware').makeMiddleware({
  proxyUrl: 'http://0.0.0.0:1335/render',
  userAgentPattern: spiderUserAgentPattern
}))

app.use(require('connect-history-api-fallback')())

app.use(require('express-static-gzip')(
  resolve('public'), {
    enableBrotli: true,
    maxAge: '1y',
    orderPreference: ['br', 'gzip', 'deflate'],
    customCompressions: [{
      encodingName: 'br',
      fileExtension: 'gz'
    }]
  }
))

app.listen(SERVER_PORT, (err) => {
  if (err) return logger.error(`Server starting error ${err}`)
  logger.info(`Server is running at http://127.0.0.1:${SERVER_PORT}`)
})